import Vue from 'vue'
import Vuex from 'vuex'
import axios from 'axios'
Vue.use(Vuex)

export default new Vuex.Store({
  state: {
    user: {}, //用户信息
    token: "",
    bm: "", //部门名称
    power: "", //权限
    past: true, //过期与否
    oldTime: "",//旧的日期
  },
  mutations: {
    //保存登陆用户信息
    login(state, data) {
      state.user = data.user
      state.token = data.token;
      state.power = data.user.power;
      state.bm = data.bm;
      // 请求头token
      axios.defaults.headers['Authorization'] = data.token;
      state.past = false;
      localStorage.setItem('user', JSON.stringify(data.user));
      localStorage.setItem('token', JSON.stringify(data.token));
      localStorage.setItem('power', JSON.stringify(data.user.power));
      localStorage.setItem('bm', data.bm);
    },
    //获取localStorage数据
    getlocalStorage(state) {
      if (localStorage.getItem('token')) {
        let length = localStorage.getItem('token').length || "";
        //注意去除token字符首尾的引号"，使用substring()方法截取
        state.token = localStorage.getItem('token').substring(1, length - 1) || "";
        state.user = JSON.parse(localStorage.getItem('user')) || {};
        state.power = localStorage.getItem('power') || "";
        state.oldTime = localStorage.getItem('oldTime') || "";
        state.bm = localStorage.getItem('bm') || "";
      }
    },
    // 过期验证
    setPast(state) {
      let newTime = new Date().getTime();
      if (state.token) {
        if (parseInt(newTime) - parseInt(state.oldTime) > 60 * 1000 * 60 * 4) { //4小时过期提示
          state.past = true;
          state.user = {};
          state.token = "";
          state.power = "";
          state.oldTime = "";
          state.bm = "";
        } else {
          state.past = false;
        }
      }
    },
    // 清空数据
    clean(state) {
      state.user = {};
      state.token = "";
      state.power = "";
      state.past = true;
      state.oldTime = "";
      state.bm = "";
      localStorage.clear();
    }
  }
})
